package org.wzl.personalwebsite.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wzl.personalwebsite._do.User;
import org.wzl.personalwebsite.dto.RegisterDTO;
import org.wzl.personalwebsite.dto.UserLoginDTO;
import org.wzl.personalwebsite.exception.BizException;
import org.wzl.personalwebsite.mapper.UserMapper;
import org.wzl.personalwebsite.service.UserService;
import org.wzl.personalwebsite.vo.RegisterVerifyCodeVO;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author 卫志龙
 * @version 1.0
 * @date 2024/9/21 20:29
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private Producer kaptchaProducer;

    @Resource
    private UserMapper userMapper;

    @Override
    public void login(UserLoginDTO userLoginDTO, HttpServletRequest request) {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, userLoginDTO.getPassword()));
        if (Objects.isNull(user)) {
            throw new BizException("登录失败，用户名不存在");
        }
        if (!userLoginDTO.getPassword().equals(user.getPassword())) {
            throw new BizException("密码错误");
        }

    }

    @Override
    public RegisterVerifyCodeVO getRegisterVerifyImg() {
        RegisterVerifyCodeVO registerVerifyCodeVO = new RegisterVerifyCodeVO();
        String base64Image;
        try {
            // 生成验证码文本
            String captchaText = kaptchaProducer.createText();

            // 生成验证码图片
            BufferedImage image = kaptchaProducer.createImage(captchaText);

            // 转换为Base64字符串
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            byte[] imageBytes = outputStream.toByteArray();
            base64Image = Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            log.error("验证码获取失败", e);
            throw new BizException("验证码获取失败");
        }

        String uuid = UUID.randomUUID().toString();

        registerVerifyCodeVO.setUuid(uuid);
        registerVerifyCodeVO.setImgBase64(base64Image);

        return registerVerifyCodeVO;
    }

    @Override
    public void register(RegisterDTO registerDTO) {

    }

}
